package com.dahaiwuliang.code.server.impl;

import com.dahaiwuliang.code.dao.MessageDao;
import com.dahaiwuliang.code.pojo.Message;
import com.dahaiwuliang.code.server.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

@Service
@Transactional
public class MessageServiceImpl implements MessageService {
    @Autowired
    private MessageDao messageDao;

    @Override
    public Page<Message> List(Integer userid, Integer page, Integer pageSize, Sort.Direction direction, String... properties) {
        return messageDao.findAll(new Specification<Message>() {
            @Override
            public Predicate toPredicate(Root<Message> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                Predicate predicate=criteriaBuilder.conjunction();
                if (userid!=null){
                   predicate.getExpressions().add(criteriaBuilder.equal(root.get("user").get("userId"),userid));
                }

                return predicate;
            }
        },PageRequest.of(page-1,pageSize,direction,properties));
    }

    @Override
    public Long getCount(Integer userId) {
        return messageDao.count(new Specification<Message>() {
            @Override
            public Predicate toPredicate(Root<Message> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                Predicate predicate=criteriaBuilder.conjunction();
                if (userId!=null){
                    predicate.getExpressions().add(criteriaBuilder.equal(root.get("user").get("userId"),userId));
                }

                return predicate;
            }
        });
    }

    @Override
    public void save(Message message) {
    messageDao.save(message);
    }

    @Override
    public Integer getCountByUserId(Integer userId) {
        return messageDao.getCountByUserId(userId);
    }

    @Override
    public void uodateState(Integer userId) {
     messageDao.uodateState(userId);
    }
}
